// src/pages/task/result/index.tsx - 任务执行结果页面
import React, { useState, useEffect } from 'react';
import { message } from 'antd';
import { getResultList } from '@/api/result';
import ResultHeader from './components/ResultHeader';
import ResultTable from './components/ResultTable';
import ResultModal from './components/ResultModal';
import { ResultItem } from './types';

const ResultPage: React.FC = () => {
  const [results, setResults] = useState<ResultItem[]>([]);
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [viewingRecord, setViewingRecord] = useState<ResultItem | null>(null);
  const [pagination, setPagination] = useState({
    page: 1,
    pageSize: 10,
    total: 0,
  });

  // 获取任务执行结果列表
  const fetchResults = async (page: number = 1, pageSize: number = 10) => {
    setLoading(true);
    try {
      const res = await getResultList(page, pageSize);

      setResults(res?.data?.items || []);
      setPagination({
        page: res?.data?.page || 1,
        pageSize: res?.data?.page_size || 10,
        total: res?.data?.total || 0,
      });
    } catch (error) {
      console.error('获取任务执行结果失败:', error);
      message.error('获取任务执行结果失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理查看详情
  const handleViewDetail = (record: ResultItem) => {
    setViewingRecord(record);
    setIsModalVisible(true);
  };

  useEffect(() => {
    fetchResults().then();
  }, []);

  const handleTableChange = (pager: any) => {
    fetchResults(pager.current, pager.pageSize).then();
  };

  return (
    <>
      <ResultHeader onRefresh={() => fetchResults(pagination.page, pagination.pageSize)} />
      <ResultTable
        results={results}
        loading={loading}
        pagination={pagination}
        onPageChange={handleTableChange}
        onViewDetail={handleViewDetail}
      />
      <ResultModal
        visible={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        result={viewingRecord}
      />
    </>
  );
};

export default ResultPage;